#include <stdio.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "pi_rw.h"
#include "pi_test.h"
#include "thread_ctrl.h"
#include "ietPiLib.h"

/* 接收线程 */
void *recv_pi_thread(void *arg)
{
    struct pi_dev_t *pdev = (struct pi_dev_t *)arg;
    struct pi_param_t *pparam = (struct pi_param_t *)pdev->parent;
    struct thread_param_t *pthread = pdev->read_thread;
    int i = 0;
    int ret = 0;
    double value = 0;
    struct PimParam devParam = {
        .type = pdev->edge,
        .window = pdev->delay,
    };

    /* 检查参数是否有效 */
    if (!pthread || !pthread->name) {
        fprintf(stderr, "Invalid parameters for %s\n", __func__);
        return NULL;
    }

    /* 线程取消 SIGUSR1 的阻塞 */
    init_thread_user_signal();
    /* 配置 PI 参数 */
    PIMInit(pdev->index, devParam);
    // printf("Start %s receive thread...\n", pdev->path);
    while (!pthread->exit_sig) {
        for (i = 0; (pparam->read_cnt == -1 || i < pparam->read_cnt) && !pthread->exit_sig; i++) {
            // nbytes = read(pdev->fd, &pdev->freq, 1);
            ret = PIMReadReal(pdev->index, &value);
            if (ret < 0) {
                fprintf(stderr, "PIMReadReal PI %d freq failed\n", pdev->index);
                break;
            } else {
                printf("PIMReadReal PI %d freq %.6lfHz\n", pdev->index, value);
            }
        }
        // printf("Read %s %d data done\n", pdev->path, pparam->read_cnt);
        break;
    }
    // printf("%s %s return\n", pdev->path, __func__);

    return NULL;
}
